package com.beiyou.orderingsystemonweb.user.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.beiyou.orderingsystemonweb.shop.dao.ShopDao;
import com.beiyou.orderingsystemonweb.shop.domain.Shop;
import com.beiyou.orderingsystemonweb.user.dao.UserDao;
import com.beiyou.orderingsystemonweb.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
public class UserService {
    @Autowired
    UserDao userDao;

    //    int addAddress(String id,String uid,String uname,String uphone,String pos,String lng,String lat);
    public int addAddress(String uid, String uname, String uphone, String pos, String lng, String lat) {
        //查询用户是否存在
        User user = userDao.queryUserByUid(uid);
        if (user == null) {
            return 0;
        }
        userDao.addAddress(UUID.randomUUID().toString().replace("-", ""), uid, uname, uphone, pos, lng, lat);
        return 1;
    }

    public void register(String acc, String pwd, String name, Integer type) {
        String id = UUID.randomUUID().toString().replace("-", "");
//        密码加密

        userDao.addLogin(id, acc, DigestUtil.md5Hex(id + pwd), type);
        userDao.addUser(id, name);
    }

    public User queryUserById(String userId) {
        return userDao.queryUserByUid(userId);
    }

    public Map<String, Object> queryOrderCountByUid(String uid) {
        Map map = new HashMap(4);
        List<Map> mapList = userDao.queryOrderCountByUid(uid);
        //应该是判断size
        if (mapList.size()==0) {
            for (int i = 1; i < 5; i++) {
                map.put("orderNum" + i, 0);
            }
            return map;
        }
        //最多4种订单
        for (int i = 1; i < 5; i++) {
            if (String.valueOf(i).equals(mapList.get(i - 1).get("orderStatue").toString())) {
                map.put("orderNum" + i, mapList.get(i - 1).get("num"));
            } else {
                map.put("orderNum" + i, 0);
            }

        }
        return map;
    }

    public List<Map> queryInterestByUid(String uid) {
        List<Shop> shops = userDao.queryInterestByUid(uid);
        List<Map> list = new ArrayList<Map>(shops.size());
        for (int i = 0; i < shops.size(); i++) {
            Map m = new HashMap();
            Shop temp = shops.get(i);
            m.put("shopId", temp.getShopId());
            m.put("shopName", temp.getShopName());

            //得到现在时间
            Calendar c = Calendar.getInstance();
            int workType = temp.getShopWorkType();
            m.put("workStatue", "暂未营业");
            //判断今天是否营业 可以通过异或
            if ((workType & (1 << ((c.get(Calendar.DAY_OF_WEEK) + 5) % 7))) > 0) {
                //判断当前是否营业--已经不需要判断星期了
                c.set(1970, 0, 1);
                if (c.getTimeInMillis() > temp.getShopBegin().getTime() && c.getTimeInMillis() < temp.getShopEnd().getTime()) {
                    m.put("workStatue", "正在营业");
                }
            }
            list.add(m);
        }
        return list;
    }

    /**
     * 购物车信息
     * 1购物车
     * 2店铺
     * 3店铺的菜品
     * 以后就这样写
     * 感觉有个生命周期的感觉:生命周期的好处就是，在不同生命周期发生不同的事情
     * 准备工作，就是创建抽象数据结构，
     * 初始化
     * 追加：快速查找（保存）
     * 结束
     */

    public Map<String, Object> queryCarByUid(String uid) {
        Map<String, Object> carMap = new HashMap();
        List<Map<String, Object>> shopList = new ArrayList();
        carMap.put("shopList", shopList);
        List<Map> mapList = userDao.queryCarByUid(uid);
        if (mapList.size()==0) {
            return null;
        }
        carMap.put("carNum", mapList.get(0).get("carNum"));
        Map<String, Map> container = new HashMap();
        for (int i = 0; i < mapList.size(); i++) {
            Map line = mapList.get(i);
            if (shopList.size() > 0) {
                Map shopMap = container.get(line.get("shopId"));
                if (shopMap != null) {
                    appendShopMap(shopMap, line);
                    continue;
                }
            }
            Map<String, Object> shopMap = new HashMap();
            shopList.add(shopMap);
            initShopMap(shopMap, line);
            saveIdAndShopMap2Container((String) line.get("shopId"), shopMap, container);
        }
        return carMap;
    }

    /**
     * 初始化-生命周期
     */
    public void initShopMap(Map<String, Object> shopMap, Map line) {
        Map<String, Object> foodMap = new HashMap<>();
        List<Map<String, Object>> foodList = new ArrayList<>();
        shopMap.put("shopId", line.get("shopId"));
        shopMap.put("shopName", line.get("shopName"));
        shopMap.put("foodList", foodList);
        foodList.add(foodMap);
        initFoodMap(foodMap, line);
    }

    /**
     * 保存
     */
    public void saveIdAndShopMap2Container(String id, Map map, Map<String, Map> container) {
        container.put(id, map);
    }

    /**
     * 追加--生命周期
     */
    public void appendShopMap(Map<String, Object> shopMap, Map line) {
        Map<String, Object> foodMap = new HashMap<>();
        List foodList = (List) shopMap.get("foodList");
        foodList.add(foodMap);
        initFoodMap(foodMap, line);
    }

    /**
     * 初始化
     */
    public void initFoodMap(Map<String, Object> foodMap, Map line) {
        foodMap.put("foodInfo", line.get("foodInfo"));
        foodMap.put("foodNum", line.get("foodNum"));
        foodMap.put("foodId", line.get("foodId"));
        foodMap.put("foodName", line.get("foodName"));
        foodMap.put("foodPrice", line.get("foodPrice"));
        foodMap.put("foodImg", line.get("foodImg"));
        //计算出来价格
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println(line.get("foodPrice"));
        BigDecimal price = new BigDecimal(line.get("foodPrice").toString());
        //单价*总量;不能强制转为String类型，不知道为什么，还是toString比较好
        foodMap.put("money", price.multiply(new BigDecimal(line.get("foodNum").toString())).toString());
    }

    /**
     * 店铺一定能找到
     * 分页查询
     */
    public Map<String, Object> userInterest(String sid, Integer begin, Integer end) {
        List<Map<String, Object>> foodList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("foodList", foodList);
        int lines = userDao.queryAllBySid(sid);
        map.put("num", lines);
        //至少有一条记录，但是菜品信息可能为空null前端正好不显示
        List<Map> mapList = userDao.queryInterestShopBySid(sid, begin, end);
        mapList.forEach(food -> {
            Map temp = new HashMap();
            temp.put("foodId", food.get("foodId"));
            temp.put("foodImg", food.get("foodImg"));
            temp.put("foodPrice", food.get("foodPrice"));
            temp.put("foodName", food.get("foodName"));
            temp.put("foodSale", food.get("foodSale"));
            temp.put("foodReport", food.get("foodReport"));
            foodList.add(temp);
        });
        map.put("shopName", mapList.get(0).get("shopName"));

        return map;
    }

    @Autowired
    ShopDao shopDao;

    //不分页了
    public Map<String, Object> queryInterestShopListByUid(String uid) {
        List<Map> mapList = userDao.queryInterestShopListByUid(uid);
        //可能没有关注
        if (mapList == null) {
            return null;
        }
        //准备
        Map<String, Object> interestMap = new HashMap<>();
        List<Map<String, Object>> interestShopList = new ArrayList<>();
        interestMap.put("interestNum", mapList.size());
        interestMap.put("interestShopList", interestShopList);
        //初始化到结束
        for (int i = 0; i < mapList.size(); i++) {
            Map temp = mapList.get(i);
            Map<String, Object> shop = new HashMap<>();
            shop.put("shopImg", temp.get("shopImg"));
            shop.put("shopName", temp.get("shopName"));
            shop.put("shopId", temp.get("shopId"));
            interestShopList.add(shop);
        }
        return interestMap;
    }

    public Map<String, Object> queryPersonByUid(String uid) {
        return userDao.queryPersonByUid(uid);
    }

    public Map<String, Object> queryCountOnMontyByUid(String uid) {
        Map<String, Object> dataMap = new HashMap<>();
        List<Map> lines = userDao.queryCountOnMontyByUid(uid);
        if (lines.size()==0) {
            //得到当前月份，说明没有
            dataMap.put("month", Calendar.getInstance().get(Calendar.MONTH) + 1);
        } else {
            //第一个记录的月份
            dataMap.put("month", lines.get(0).get("month"));
            //准备
            List<Map<String, Object>> dataList = new ArrayList<>(lines.size());
            dataMap.put("DataList", dataList);
            lines.forEach(map -> {
                Map<String, Object> temp = new HashMap<>();
                temp.put("money", map.get("money"));
                temp.put("discount", map.get("discount"));
                BigDecimal sum1 = new BigDecimal(map.get("money").toString());
                BigDecimal sum2 = new BigDecimal(map.get("discount").toString());
                BigDecimal sum3 = sum2.add(sum1);
                temp.put("sum", sum3.toString());
                dataList.add(temp);
            });
        }
        return dataMap;
    }

    public Map<String, Object> queryUserOrderInfoByUserId(String uid) {
        Map<String, Object> map = new HashMap<>();
        //准备
        List<Map> lines = userDao.queryUserOrderInfoByUserId(uid);
        if (lines.size() > 0){
            Map first = lines.get(0);
            map.put("userName", first.get("userName"));
            map.put("userId", first.get("userId"));
            map.put("userImg", first.get("userImg"));
            Map<String,Map<String,Object>> orderStatus = new HashMap<>();
            if (first.get("foodName") != null) {
                List<Map<String, Object>> orderList = new ArrayList<>();
                map.put("orderList", orderList);
                lines.forEach(line -> {
                    if (orderStatus.get(line.get("orderStatue").toString()) != null) {
                        iniOrderMap(orderStatus.get(line.get("orderStatue").toString()), line);
                    } else {
                        Map<String, Object> orderMap = new HashMap<>();
                        iniOrderMap(orderMap, line);
                        orderList.add(orderMap);
                        orderStatus.put(line.get("orderStatue").toString(), orderMap);
                    }
                });
            }
        }
        else {
            map.put("orderMsg", "没有找到您的订单信息，抱歉");
            return null;
        }
        return map;
    }
//先创建在初始化比较好。这个顺序错了非常麻烦
    public void iniOrderMap(Map<String, Object> orderMap, Map line) {
        //准备-建立其它对象
        List<Map<String, Object>> foodList = new ArrayList<>();
        Map<String, Object> foodMap = new HashMap<>();
        orderMap.put("foodList", foodList);
        foodList.add(foodMap);
        //初始化其它对象
        orderMap.put("orderStatue", getStatueNameByOrderSattue(line.get("orderStatue").toString(),foodMap,line));
        initOrderFoodMap(foodMap, line);
    }

    public void initOrderFoodMap(Map<String, Object> foodMap, Map line) {
        //添加菜品名
        foodMap.put("foodName", line.get("foodName"));
    }

    //订单值为1
    public void initOrderStatue1(Map foodMap, Map line) {

    }

    public void initOrderStatue2(Map foodMap, Map line) {
        foodMap.put("orderName",line.get("orderName"));
        foodMap.put("orderPhone",line.get("orderPhone"));
    }

    public void initOrderStatue3(Map foodMap, Map line) {
        foodMap.put("foodId",line.get("foodId"));
    }

    public void initOrderStatue4(Map foodMap, Map line) {
        foodMap.put("orderNum",line.get("orderNum"));
    }

    //通过 订单状态得到订单名
    public String getStatueNameByOrderSattue(String orderSattue,Map foodMap, Map line) {
        switch (orderSattue) {
            case "1":
                initOrderStatue1(foodMap,line);
                return "待送餐";
            case "2":
                initOrderStatue2(foodMap,line);
                return "送餐中";
            case "3":
                initOrderStatue3(foodMap,line);
                return "待评论";
            default:
                initOrderStatue4(foodMap,line);
                return "待接单";
        }
    }
}
